﻿using System;
using System.Collections;
using System.Collections.Generic;

namespace Integrity
{
  public class ManyToMany<TOwner, TValue> : ICollectonProp<TOwner, TValue>
    where TValue : class
    where TOwner : class
  {
    public bool CascadeDeletion { get; private set; }
    public ManyToMany<TValue, TOwner> CorrProp { get { return _corrProp(); } }

    private readonly Func<TOwner, ICollection<TValue>> _storageGetter;
    private readonly Func<ManyToMany<TValue, TOwner>> _corrProp;

    public ManyToMany(Func<TOwner, ICollection<TValue>> storageGetter, Func<ManyToMany<TValue, TOwner>> corrProp, bool cascadeDeletion)
    {
      CascadeDeletion = cascadeDeletion;
      Integrity.Register<TOwner>(this);
      _storageGetter = storageGetter;
      _corrProp = corrProp;
    }

    public ICollection<TValue> GetValue(TOwner owner)
    {
      return _storageGetter(owner);
    }

    public void Reset(TOwner owner)
    {
      GetValue(owner).Clear();
    }

    object IProperty.GetValue(object owner) { return GetValue((TOwner)owner); }
    IList ICollectonProp.GetValue(object owner) { return (IList)GetValue((TOwner)owner); }
    void IProperty.Reset(object owner) { Reset((TOwner)owner); }
    bool IProperty.IsCollection { get { return true; } }
    RelationKind IProperty.Relation { get { return RelationKind.ManyToMany; } }
    IProperty IProperty.CorrProp { get { return CorrProp; } }
  }
}